import { Tabs,Button,Form, Modal,message,Row,Col, Spin} from 'antd';
import PropTypes from 'react-router/lib/PropTypes';
const TabPane = Tabs.TabPane;
const createForm = Form.create;
const FormItem = Form.Item;
import isEmpty from 'lodash/isEmpty'
import debounce from 'lodash/debounce'
import Immutable from 'immutable'
import isArray from 'lodash/isArray'
const is = Immutable.is;

import { WeaErrorPage, WeaTools,WeaSearchBrowserBox,WeaTableEdit, WeaDialog,WeaSearchGroup, WeaRightMenu } from 'ecCom'
import '../../css/myCard-basicInfo.less';
import { InfoGroup4Formal1,InfoGroup4Formal2} from '../public/infoGroup4Formal';

import {createQRCode} from '../../utils'
import * as PublicFunc from '../../utils/pulic-func';
import TopButton from '../public/topButton';
import * as MyCardAction from '../../actions/myCard';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {getParamsByConditions, formatFieldsByParams, validate} from '../../utils'

let __this;
class BasicInfo4Formal extends React.Component {
    static contextTypes = {
        router: PropTypes.routerShape,
    }
    constructor(props) {
        super(props);
        const funcs = ['onRightMenuClick', 'showSQR','editCard','backCard','saveEditCard'];
        funcs.forEach(f=> this[f] = this[f].bind(this))
        this.state={
            tabs:[],
            activeKey:'HrmResourceBase',
            modelItems:[],
            datas:[],
            infoGroup:[],
            infoGroup2:[],
            imgSrc:null,
            hrmInfo:[],
            sendButtons: [],
            accountInfo:[],
            showSQR:false,
            showBigImg: false,
            showAccountInfo:false,
            isEditor:false,
            buttons: {},
        }
        __this = this;
    }
    getDatas(datas){
        let infoGroup=[];//信息组
        let imgSrc=null;//人员照片
        let hrmInfo=[];//我的卡片顶部信息
        let sendButtons= [];
        let accountInfo=[];
        datas && datas.forEach(d=>{
            if(d.id=='item1'){
                hrmInfo = d.items;
            }
            if(d.id=='item2'){
                d.items.forEach(d2=>{
                    d2.name == 'resourceimageid' && (imgSrc = d2.value)
                    d2.hasSendButton && (sendButtons = d2.options);
                    d2.accountinfo && (accountInfo = d2.accountinfo)
                })
            }
            if(d.id=='item4' || d.id=='item5') infoGroup.push(d);
        })
        this.setState({
            datas,
            infoGroup,
            imgSrc,
            hrmInfo,
            sendButtons,
            accountInfo,
        })
    }
    init() {
        const hrmId = this.props.params.hrmId;
        Promise.all([
            WeaTools.callApi('/api/hrm/resource4formal/getResourceCard','GET',
                {operation:'getResourceBaseView',id:hrmId, noLoadData: 1})
            ,
            WeaTools.callApi('/api/hrm/resource4formal/getResourceCard','GET',
                {operation:'getResourceBaseView',id:hrmId, cmd:'getResourceBaseData', noLoadData: 1})
            ,
            WeaTools.callApi('/api/hrm/resource/getHrmResourceItem','GET',{id:hrmId,  noLoadData: 1})
        ]).then( res=> {
            __this.getDatas(res[0].result);
            __this.setState({infoGroup2: res[1].result, buttons: res[0].buttons})
            __this.setState({modelItems:res[2]})
            WeaTools.callApi('/api/hrm/resource4formal/getResourceCard','GET',{operation:'getResourceBaseView',id:hrmId}).then(datas=>{
                __this.getDatas(datas.result);
            }),
            WeaTools.callApi('/api/hrm/resource4formal/getResourceCard','GET',{operation:'getResourceBaseView',id:hrmId,cmd:'getResourceBaseData'}).then(datas=>{
                __this.setState({infoGroup2:datas.result})
            })
             WeaTools.callApi('/api/hrm/resource/getHrmResourceItem','GET',{id:hrmId}).then(datas=>{
                __this.setState({modelItems:datas})
            })
        })
    }
    componentDidMount(){
        this.init();
        const hrmId = this.props.params.hrmId;
        WeaTools.callApi('/api/hrm/resource/getQRCode','GET',{id:hrmId}).then(obj=>{
            obj.hasQRCode && createQRCode(obj.options);
        }).catch(err=>{
            message.error(err);
        });
    }
    // shouldComponentUpdate(nextProps, nextState) {
    //     return  !is(this.state.datas,nextState.datas) ||
    //         !is(this.state.modelItems,nextState.modelItems)||
    //         this.state.showSQR !== nextState.showSQR||
    //         this.state.showBigImg !== nextState.showBigImg||
    //         this.state.showAccountInfo !== nextState.showAccountInfo||
    //         this.props.isEditor !== nextProps.isEditor

    // }
    componentWillUnmount() {
        const {actions} = this.props;
        actions.saveFormFields();
    }
    showSQR(bool,e){
        const {showSQR}=this.props;
        e.stopPropagation && e.stopPropagation();
        e.preventDefault && e.preventDefault();
        e.nativeEvent && e.nativeEvent.preventDefault();
        this.setState({showSQR:bool});
    }
    getIcon(str) {
        switch(str){
            case 'sendEmessage':
                return 'icon-coms-Send-message';
            case 'openmessage':
                return 'icon-coms-message-o';
            case 'openemail':
                return 'icon-coms-Send-emails';
            case 'doAddWorkPlan':
                return 'icon-coms-New-schedule';
        }
    }
    getRightMenu(){
        const {isEditor, buttons} = this.state;
        let arr = [];
        if (isEditor){
            if (buttons.hasSave) {
                arr = [{
                    icon: <i className='icon-coms-ws'/>,
                    content:'保存'
                }, {
                    icon: <i className='icon-coms-ws'/>,
                    content:'返回'
                }]
            }
        } else {
            if (buttons.hasEdit) {
                arr = [{
                        icon: <i className='icon-coms-ws'/>,
                        content:'编辑'
                }]
            }
        }
        return arr;
    }
    onRightMenuClick(key){
        const {isEditor} = this.state;
        if (isEditor) {
            switch(key){
                case '0':
                    this.saveEditCard();
                    break;
                case '1':
                    this.backCard();
                    break;
            }
        } else {
            switch(key){
                case '0':
                    this.editCard();
                    break;
            }
        }
    }
    getTopButtons() {
        const {isEditor, buttons} = this.state;
        const save = <Button type="primary" disabled={false} onClick={this.saveEditCard} >保存</Button>;
        const back = <Button disabled={false} onClick={this.backCard} >返回</Button>;
        const edit = <Button type="primary" disabled={false} onClick={this.editCard} >编辑</Button>;
        const btns = [];
        if (isEditor) {
            if (buttons.hasSave) {
                btns.push(save);
                btns.push(back);
            }
        } else {
            if (buttons.hasEdit) {
                btns.push(edit);
            }
        }
        return btns;
    }
    editCard(){
        const {conditioninfo} = this.state;
        const {actions,params} = this.props;
        WeaTools.callApi('/api/hrm/resource/getResourceCard', 'GET', {
            operation: 'getResourceBaseView', viewattr: 2, id: params.hrmId
        }).then((data)=>{
            this.setState({conditioninfo: data.result.conditions});
            let params = getParamsByConditions(data.result.conditions);
            let field = formatFieldsByParams(params);
            actions.saveFormFields(field);
        })
        this.setState({isEditor:true});
    }
    saveEditCard(){
        const {fieldParams, params, actions} = this.props;
        const {conditioninfo} = this.state;
        const hrmId = params.hrmId;
        if (validate(conditioninfo, fieldParams.toJS())){
            WeaTools.callApi('/api/hrm/resource/editResource','POST',
                {...{operation:'editresourcebasicinfo', id: hrmId}, ...fieldParams.toJS()}).
            then(data=>{
                if (data.status == '1') {
                    message.success('保存成功!');
                    this.init();
                    actions.saveFormFields();
                    this.setState({isEditor:false});
                } else {
                    message.warning(data.message);
                }

            }, error=> {
                message.warning(error.message);
            })
        }
    }
    backCard(){
        this.setState({isEditor:false});
    }
    render() {
        const {isEditor, infoGroup,infoGroup2,imgSrc,modelItems,showSQR,showBigImg,sendButtons,accountInfo,showAccountInfo}=this.state;

        const getPortrait =()=>{
            const loadingImg = '/images/messageimages/temp/loading_wev8.gif';
            return (
                <div className='hrm-my-card-basicInfo-left-imgwrap'>
                    <div className='hrm-my-card-basicInfo-left-imgwrap-triangle' onClick={debounce(this.showSQR.bind(null,true),150)}/>
                    {!showBigImg &&
                        <img className='hrm-my-card-basicInfo-left-img'
                            src={imgSrc ? imgSrc : loadingImg}
                            onError={()=> {this.setState({imgSrc: '/images/messageimages/temp/man_wev8.png'})}}
                            onClick={()=>imgSrc && this.setState({showBigImg:true})}
                        />
                    }
                    {showBigImg &&
                        <img className='hrm-my-card-basicInfo-left-img-big'
                            onError={()=> {this.setState({imgSrc: '/images/messageimages/temp/man_wev8.png'})}}
                            onClick={()=>imgSrc && this.setState({showBigImg:false})}
                            src={imgSrc ? imgSrc : loadingImg}
                        />
                    }
                    <div className='hrm-my-card-basicInfo-left-img-sqrimg' style={{position:'absolute',top:4,right:5}} onClick={debounce(this.showSQR.bind(null,true),150)}>
                        <i className='icon-coms-Scan' style={{color:'#fff'}}/>
                    </div>
                    <div className='hrm-my-card-basicInfo-sqr' style={{display: showSQR ? 'block' : 'none'}} onClick={this.showSQR.bind(null,false)}/>
                </div>
            )
        }
        const getPortraitButtons=()=>{
            const colArr = [];
            isArray(sendButtons) && sendButtons.forEach((item) => {
                colArr.push(
                    <Col span={6}>
                        <div className='hrm-my-card-basicInfo-icon-circle'
                            onClick={()=> {
                                PublicFunc[item.funname](item.id);
                            }}
                            title={item.title}
                        >
                            <i className={`${this.getIcon(item.name)}`}></i>
                        </div>
                    </Col>
                )
            })
            return colArr;
        }
        const getAccountinfo=()=>{
            let colArr = [];
             accountInfo && accountInfo.forEach((a,i)=>{
                if(a.name=='weixin'){
                    colArr.push(
                        <Col className='hrm-my-card-basicInfo-left-accountinfo-label' span='24'>
                            <a onClick={()=> {showWeaDialog()}}>{a.label}</a>
                        </Col>
                    );
                }else{
                    colArr.push(
                        <Col className='hrm-my-card-basicInfo-left-accountinfo-label' span='12'>
                        {a.label} :
                        </Col>
                    );
                    colArr.push(
                        <Col className='hrm-my-card-basicInfo-left-accountinfo-value' span='12'>
                        {a.value ? <span dangerouslySetInnerHTML={{__html:a.value}}/> : <div>&nbsp;</div>}
                        </Col>
                    );
                }

                i==3 && colArr.push(<Col className='hrm-my-card-basicInfo-left-accountinfo-middline' span='24'/>);

            });
            if(!showAccountInfo){
                colArr.splice(8,colArr.length);
            }
            colArr.push(
                <Col className='hrm-my-card-basicInfo-left-accountinfo-endicon' span='24' onClick={()=>this.setState({showAccountInfo:!showAccountInfo})}>
                    <i className={showAccountInfo ? 'icon-coms-up' : 'icon-coms-down'} title={showAccountInfo ? '收起' : '展开'}/>
                </Col>
            );
            return colArr;
        }
        const viewCard = (
                <div className='hrm-my-card-basicInfo' style={{height:'100%'}}>
                    <WeaDialog style={{width:500, height: 380}} title={'微信企业号绑定'} hideIcon>
                        <div className='align-center'>
                            <img src="/hrm/resource/image/qrcode.jpg" style={{height: 374, width: 344}}/>
                        </div>
                    </WeaDialog>
                    <div className='hrm-my-card-basicInfo-left' >
                        {getPortrait()}
                        <Row className="hrm-my-card-basicInfo-left-imgwrap-op"  type="flex" justify="center" gutter={16}>{getPortraitButtons()}</Row>
                        <Row>{getAccountinfo()}</Row>
                    </div>
                    <div className='hrm-my-card-basicInfo-right'>
                        <div className='hrm-my-card-basicInfo-right-counts'>
                        {
                            modelItems && modelItems.map(c => {
                                const fontColor = c['font-color'];
                                return (
                                    <div className='hrm-my-card-basicInfo-right-counts-cell' >
                                        <img src={c.icon} alt=""/>
                                        <div className='hrm-my-card-basicInfo-right-counts-cell-info'>
                                            <div>{c.label}</div>
                                            <div title={c.num} className='text-overflow'><a href={c.url} style={fontColor?{color:fontColor}:null} target='_blank'>{c.num}</a></div>
                                        </div>
                                    </div>
                                )
                            })
                        }
                        </div>
                        <Row gutter={24}>
                            <Col span='12'>
                                <Row className='hrm-my-card-basicInfo-right-info'>
                                    {
                                        infoGroup && infoGroup.map(info => {
                                            return (
                                                <Col span='24'>
                                                    <InfoGroup4Formal1 items={info.items} title={info.title} showGroup={info.defaultshow}/>
                                                </Col>
                                            )
                                        })
                                    }
                                </Row>
                            </Col>
                            <Col span='12'>
                                <Row className='hrm-my-card-basicInfo-right-info'>
                                 {
                                        infoGroup2 && infoGroup2.map(info => {
                                            return (
                                                <Col span='24'>
                                                    <InfoGroup4Formal2 items={info.items} title={info.title} showGroup={info.defaultshow}/>
                                                </Col>
                                            )
                                        })
                                    }
                                </Row>
                            </Col>
                        </Row>
                    </div>
                </div>
        )
        const editCard = (
            <div className='hrm-my-card-basicInfo' style={{height:'100%'}}>
                {this.getSearchs()}
            </div>
        )
        return (<div style={{position: 'relative'}}>
                <TopButton
                    buttons={this.getTopButtons()}
                    buttonSpace={10}
                    showDropIcon={true}
                    dropMenuDatas={this.getRightMenu()}
                    onDropMenuClick={this.onRightMenuClick}
                />
                <WeaRightMenu
                    datas={this.getRightMenu()}
                    onClick={this.onRightMenuClick}
                >
                    {!isEditor ? viewCard : editCard}
                </WeaRightMenu>
            </div>)
    }
    getSearchs(){
        const { conditioninfo } = this.state;
        let group = [];
        conditioninfo && conditioninfo.forEach(c =>{
            let items = [];
            c.items.forEach( field => {
                items.push({
                    com:(<FormItem
                        label={`${field.label}`}
                        labelCol={{span: `${field.labelcol}`}}
                        wrapperCol={{span: `${field.fieldcol}`}}>
                            {WeaTools.getComponent(field.conditionType,field.browserConditionParam,field.domkey,this.props,field)}
                        </FormItem>),
                    colSpan: 1
                });
            });
            group.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
        });
        return <Form horizontal>{group}</Form>
    }
}

//组件检错机制
class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return(
            <WeaErrorPage msg={ hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！" } />
        );
    }
}


BasicInfo4Formal = WeaTools.tryCatch( React, MyErrorHandler, { error: "" })(BasicInfo4Formal);
//form 表单与 redux 双向绑定
BasicInfo4Formal = createForm({
    onFieldsChange(props, fields) {
        props.actions.saveFormFields({...props.fields.toJS(), ...fields});
    },
    mapPropsToFields(props) {
        return props.fields.toJS();
    }
})(BasicInfo4Formal);

// 把 state map 到组件的 props 上
const mapStateToProps = state => {
  const {hrmMyCardCore} = state;
  return {
    fields: hrmMyCardCore.get('fields'),
    fieldParams: hrmMyCardCore.get('fieldParams'),
  }
}

const mapDispatchToProps = dispatch => {
  return {
    actions: bindActionCreators(MyCardAction, dispatch)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(BasicInfo4Formal);